package com.hxzy.system.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.common.constant.UserConstants;
import com.hxzy.common.core.domain.TreeSelect;
import com.hxzy.common.core.domain.entity.SysDept;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.utils.StringUtils;
import com.hxzy.system.domain.dto.SysDeptSearchDTO;
import com.hxzy.system.mapper.SysDeptMapper;
import com.hxzy.system.service.ISysDeptService;
import org.springframework.context.annotation.Lazy;

import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 部门管理
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper,SysDept> implements ISysDeptService {


    /**
     * 查询部门列表
     * @param sysDeptSearchDTO 部门信息
     * @return
     */
    @Override
    public List<SysDept> selectDeptList(SysDeptSearchDTO sysDeptSearchDTO) {
        List<SysDept> deptList=this.baseMapper.selectDeptList(sysDeptSearchDTO);
        return deptList;
    }

    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        return null;
    }

    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts) {
        return null;
    }

    @Override
    public List<Long> selectDeptListByRoleId(Long roleId) {
        return null;
    }

    @Override
    public SysDept selectDeptById(Long deptId) {
        return null;
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     * @param deptId 部门ID
     * @return
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        return this.baseMapper.selectNormalChildrenDeptById(deptId);
    }

    @Override
    public boolean hasChildByDeptId(Long deptId) {
        return false;
    }

    @Override
    public boolean checkDeptExistUser(Long deptId) {
        return false;
    }

    /**
     * 检查部门名称是否重复
     * @param dept
     * @return
     */
    @Override
    public String checkDeptNameUnique(SysDept dept) {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = this.baseMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());

        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;

    }

    @Override
    public void checkDeptDataScope(Long deptId) {

    }

    @Override
    public boolean insertDept(SysDept dept) {
        SysDept info = this.getById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new ServiceException("部门停用，不允许新增");
        }

        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return this.save(dept);
    }

    @Override
    public int updateDept(SysDept dept) {
        SysDept newParentDept = this.baseMapper.selectDeptById(dept.getParentId());

        SysDept oldDept = this.baseMapper.selectDeptById(dept.getDeptId());

        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = this.baseMapper.updateById(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;
    }

    @Override
    public int deleteDeptById(Long deptId) {
        return 0;
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<SysDept> children = this.baseMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            this.baseMapper.updateDeptChildren(children);
        }
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept)
    {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        this.baseMapper.updateDeptStatusNormal(deptIds);
    }

}
